﻿using System;
using Windows.Foundation;

namespace LinkPad.Helpers
{
    public static class GeometryHelper
    {
        #region Methods

        public static double Distance(double x1, double y1, double x2, double y2)
        {
            var d = Math.Sqrt(Math.Pow((x2 - x1), 2) + Math.Pow((y2 - y1), 2));
            return d;
        }

        public static double Distance(this Point pt1, Point pt2)
        {
            return Distance(pt1.X, pt1.Y, pt2.X, pt2.Y);
        }

        public static double DiagonalLength(this Rect rect)
        {
            return Distance(rect.Left, rect.Top, rect.Right, rect.Bottom);
        }

        public static Rect ExpandRect(this Rect rect, double erx, double ery)
        {
            var newWidth = rect.Width*erx;
            var newHeight = rect.Height*ery;
            var diffx = (newWidth - rect.Width)*0.5;
            var diffy = (newHeight - rect.Height)*0.5;
            var result = new Rect(rect.X - diffx, rect.Y - diffy, newWidth, newHeight);
            return result;
        }

        public static double DistanceLineSegmentToPoint(double x1, double y1, double x2, double y2, double ptX, double ptY)
        {
            var dx = x2 - x1;
            var dy = y2 - y1;
            var r = Math.Sqrt(dx * dx + dy * dy);
            var cosa = dx / r;
            var sina = dy / r;

            var shiftedX = ptX - x1;
            var shiftedY = ptY - y1;

            var rotatedX = shiftedX * cosa + shiftedY * sina;
            var rotatedY = -shiftedX * sina + shiftedY * cosa;

            if (rotatedX < 0)
            {
                return Math.Sqrt(rotatedX * rotatedX + rotatedY * rotatedY);
            }
            if (rotatedX > r)
            {
                var xvr = rotatedX - r;
                return Math.Sqrt(xvr * xvr + rotatedY * rotatedY);
            }
            return Math.Abs(rotatedY);
        }

        #endregion
    }
}
